package shoppersservlets;

import infraestructura.PersistenceManager;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import modelo.Comment;
import modelo.Validador;

@WebServlet(name = "Comments", urlPatterns = {"/comments"})
public class Comments extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int idProducto = Integer.parseInt(request.getParameter("idProducto"));
        String comment = request.getParameter("comentario");
        if (Validador.esEntradaNoValida(comment)) {
            request.getRequestDispatcher("./").forward(request, response);
        } else {
            PersistenceManager manager = PersistenceManager.getPersistenceManager(getServletContext().getInitParameter("persistenceMethod"));
            manager.addComment(new Comment(idProducto, comment));
            request.getRequestDispatcher("./producto?id=" + request.getParameter("idProducto")).forward(request, response);
        }

    }

    @Override
    public String getServletInfo() {
        return "Comentarios";
    }
}
